package com.lqb.webScaffold.utils;

import com.lqb.webScaffold.config.MinioConfig;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Component
public class MinioUtils {

    @Autowired
    MinioConfig minioConfig;

    @Autowired
    MinioClient minioClient;

    public String uploadFile(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            String fileName = generateUniqueFileName(file.getOriginalFilename());
            String contentType = file.getContentType();
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getMinioBucketName())
                            .object(fileName)
                            .stream(inputStream, inputStream.available(), -1)
                            .contentType(contentType)
                            .build()
            );
            return fileName;
        }catch (Exception exception){
            exception.printStackTrace();
            return null;
        }
    }

    public void downloadFile(String fileName,HttpServletResponse res) throws Exception {
        InputStream response = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(minioConfig.getMinioBucketName())
                        .object(fileName)
                        .build()
        );
        byte[] buf = new byte[1024];
        int len;
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        while ((len = response.read(buf)) != -1) os.write(buf, 0, len);
        os.flush();
        byte[] bytes = os.toByteArray();
        res.setCharacterEncoding("utf-8");
        res.setContentType("application/force-download");
        res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        ServletOutputStream stream = res.getOutputStream();
        stream.write(bytes);
        stream.flush();
    }

    private String generateUniqueFileName(String originalFileName) {
        return System.currentTimeMillis() + "-" + StringUtils.cleanPath(originalFileName);
    }
}

